package com.java.demo.model;

import java.util.ArrayList;

/**
 * 观察者模式
 *
 * @auther zhangwj
 * @date 2020/12/30 下午4:41
 */
public class ObserverPattern {

    public static void main(String[] args) {
        WeatherData weatherData = new WeatherData();
        ThirdPartyDisplay thirdPartyDisplay =   new ThirdPartyDisplay(weatherData);
        weatherData.setMeasurements(10,20,40);
        thirdPartyDisplay.display();
        weatherData.setMeasurements(15,25,45);
        thirdPartyDisplay.display();
    }
}

class WeatherData implements Subject {

    public void measurementsChanged() {
        notifyObservers();
    }

    private ArrayList<Observer> observers;

    WeatherData() {
        observers = new ArrayList<>();
    }

    // 温度
    private int temperature;

    // 湿度
    private int humidity;

    // 压强
    private int pressure;

    @Override
    public void register(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void remove(Observer observer) {
        int index = observers.indexOf(observer);
        if (index > 0) {
            observers.remove(index);
        }
    }

    @Override
    public void notifyObservers() {
        if (observers.size() > 0) {
            observers.forEach(observer -> observer.update(temperature, humidity, pressure));
        }
    }

    public void setMeasurements(int temperature, int humidity, int pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}

interface Subject {

    void register(Observer observer);

    void remove(Observer observer);

    void notifyObservers();
}

interface Observer {

    void update(int temperature, int humidity, int pressure);
}

interface DisplayElement {

    void display();
}

// 第三方显示
class ThirdPartyDisplay implements Observer, DisplayElement {

    private int temperature;

    private int humidity;

    private int pressure;

    private Subject weatherData;

    ThirdPartyDisplay(Subject weatherData) {
        this.weatherData = weatherData;
        weatherData.register(this);
    }

    @Override
    public void update(int temperature, int humidity, int pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
    }

    // 现实基于观测值的其他内容
    @Override
    public void display() {
        System.out.println("显示屏幕: temperature=" + temperature + ",humidity=" + humidity + ",pressure=" + pressure);
    }
}